//
//  HLOAuthViewModel.swift
//  MyBlog
//
//  Created by 李芙蓉 on 16/3/5.
//  Copyright © 2016年 hanlei. All rights reserved.
//

import UIKit

class HLOAuthViewModel: NSObject {
    
    //快速创建单例方法
    static let sharedOAuthViewModel : HLOAuthViewModel = HLOAuthViewModel()
    
    private override init() {
        
    }
    
    //保存模型数据
    var userAccount : HLAccount?
    
    //获取AccessToken
    func loadAccessToken(appCode:String, appKey:String, appSecret:String, redictUri:String, callBack:(success:Bool)->()) {
        
        let urlString : String = "https://api.weibo.com/oauth2/access_token"
        
        let parameter : [String:AnyObject] = ["client_id":appKey,"client_secret":appSecret,"grant_type":"authorization_code","code":appCode,"redirect_uri":redictUri]
        
        HMNetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameter) { (responseObject, error) -> () in
            
            if error == nil {
                
                if let response = responseObject {
                    
                    self.userAccount = HLAccount(dict: response)
                    
                    self.loadUserInfomation(self.userAccount!,callBack: callBack)
                }
                
            } else {
                
                callBack(success: false)
            }
        }
    }
    
    //获取用户信息
    private func loadUserInfomation(userAccount:HLAccount, callBack:(success:Bool)->()) {
    
        let urlString : String = "https://api.weibo.com/2/users/show.json?access_token=\(userAccount.access_token!)&uid=\(userAccount.uid)"
        print(urlString)
        HMNetworkTools.sharedTools.requst(.GET, urlString: urlString, parameters: self) { (responseObject, error) -> () in
            
            if error == nil {
                
                if let response = responseObject {
                    
                    userAccount.profile_image_url = response["profile_image_url"] as? String
                    
                    self.encode()
                    
                    callBack(success: self.isSuccessCallBack())
                }
//                2021-03-04 15:28:17 +0000
            } else {
                
                callBack(success: false)
            }
        }
    }
    
    //判断是否是成功回调
    func isSuccessCallBack () -> Bool {
        
        //判断accessToken是否过期
        if let result = userAccount?.expireTime.compare(NSDate()) {
            
            if result == NSComparisonResult.OrderedDescending {
                
                return true
            }
        }
        
        return false
    }
    
    //归档方法
    private func encode () {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("keyArchive.archive")
        
        NSKeyedArchiver.archiveRootObject(userAccount!, toFile: path)
    }
    
    //解档方法
    private func decode () -> HLAccount{
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("keyArchive.archive")
        
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as! HLAccount
    }
}
